using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.StepTasks.Commands;

/// <summary>
/// 重组工步顺序号。
/// </summary>
/// <param name="StepId">工艺步骤 Id</param>
public sealed record ReorganizeStepTaskSeqCommand(long StepId) : IRequest<IResult<bool>>;

internal sealed class ReorganizeStepTaskSeqCommandHandler(IRepository<ProcStepTask> repo) : IRequestHandler<ReorganizeStepTaskSeqCommand, IResult<bool>>
{
    const int GroupSpan = 1000; // 分组区间

    public async Task<IResult<bool>> Handle(ReorganizeStepTaskSeqCommand request, CancellationToken cancellationToken)
    {
        // 以 1000 为单位重组 seq
        var stepTasks = await repo.GetListAsync(m => m.StepId == request.StepId, m => m.Seq, false, cancellationToken);
        if (stepTasks.Count == 0)
        {
            return Result.From(true);
        }

        List<ProcStepTask> stepTasks1 = [];
        foreach (var span in stepTasks.Select(s => s.Seq / GroupSpan).Distinct())
        {
            int startSpan = span * GroupSpan;
            int start = startSpan + 1;
            foreach (var stepTask in stepTasks.Where(s => startSpan < s.Seq && s.Seq < startSpan + GroupSpan))
            {
                if (stepTask.Seq != start)
                {
                    stepTask.Seq = start;
                    stepTasks1.Add(stepTask);
                }

                start++;
            } 
        }

        if (stepTasks1.Count > 0)
        {
            await repo.UpdateAsync(stepTasks1, m => new
            {
                m.Seq
            }, cancellationToken);
        }

        return Result.From(true);
    }
}
